#!/bin/sh
#
# Simple script that removes unused packages (packages that were installed as dependencies but are no longer required by any installed package.)
#
#
# Package remove loop, removes every package in $PKGLIST and checks for more
# because pacman sometimes doesn't show every package.

## Check root access
[ "$(whoami)" != "root" ] && echo "You must be a root user." && exit 1

## Set variable
TOTALPKG=0

## Start loop
##
## `pacman -Qdt | wc -l` equals to number of packages in the package list
##
while [ "$(pacman -Qdt | wc -l)" -ge "1" ]
do
	## $PKGLIST variable parses pacmans output to be able to use it in for loop
	PKGLIST=$(pacman -Qdt | sed -e 's/\ .*//g')
	
	for PACKAGE in $PKGLIST
	do
		pacman -R "$PACKAGE"
		
		TOTALPKG=$((TOTALPKG + 1))
	done
done

## Final output 
[ "$TOTALPKG" -ge "1" ] && printf "%s package/s removed.\\n" "$TOTALPKG" || printf "There is no package to remove.\\n"

